//*** Guidance generated code ***//
using System;
using System.Collections.Generic;
using System.Linq;

using ProjectBase.Core;

using $prjsn$.Entity;
using $prjsn$.Common;
using $prjsn$.Common.Validation;
using $prjsn$.Common.Data;
using $prjsn$.Common.Business;

namespace $safeprojectname$
{
    public class CustomListTypeFilterValidator : FilterValidatorBase<CustomListType, CustomListTypeFilter, int>
    {
        protected override void Init(RuleCollection<CustomListTypeFilter> rules)
        {
            base.Init(rules);
        }
    }

    public class CustomListTypeValidator : CodeListValidator<CustomListType, ICustomListTypeDao>
    {
        protected override void Init(RuleCollection<CustomListType> rules)
        {
            base.Init(rules);

            // unique Description, Parent
            rules.For(entity => entity.Description).RequireLengthBetween(1, 50).BreakOnError();

            rules.IsUnique(entity => Dao.Find(entity.ID,
                new CustomListTypeFilter
                {
                    DescriptionExact = entity.Description,
                }
            ), "Description");

            // Delete
            rules.Assure(IsCustomListTypeInUse).WhenDeleting();
        }

        #region Check

        protected virtual ValidationResult IsCustomListTypeInUse(CustomListType entity, out ValidationMessage message)
        {
            message = null;

            var usedByCustomListType = CustomListFacade
                .Find(new CustomListFilter { CustomListType = entity, TakeRows = 1 })
                .FirstOrDefault();

            if (usedByCustomListType.Is())
            {
                message = new ValidationMessage(Str.Messages.ItemIsUsedForEntity4)
                {
                    entity,
                    usedByCustomListType,
                    Str.Controllers.CustomListType,
                    Str.Controllers.CustomListType,
                };
                return ValidationResult.Error;
            }

            return ValidationResult.IsValid;
        }

        #endregion Check

        public virtual ICustomListFacade CustomListFacade { protected get; set; }
    }
}